<template>
  <div id="nav-header">
    <div class="nav">
      <el-menu
        default-active="home"
        class="el-menu-demo"
        mode="horizontal"
        text-color="#f3f9f1"
        active-text-color="#e0eee8"
        router
        style="background-color: rgb(80,97,109,0.8);border: 0;"
      >
        <el-menu-item class="logoItem" index="home" route="/home">
          <img src="@/assets/logo.png" style="width:45px; height: 45px;" />
        </el-menu-item>
        <el-menu-item index="media" route="/media">媒体</el-menu-item>
        <el-menu-item index="game" route="/game">游戏</el-menu-item>
        <el-menu-item
          v-if="$store.state.token == ''"
          class="login-Item"
          @click="loginVisible = true;"
          style="float:right;"
        >
          <i class="el-icon-user"></i>登陆
        </el-menu-item>
        <el-menu-item
          v-else
          class="login-Item"
          index="person"
          route="/userInfo"
          style="float:right;"
        >
          <i class="el-icon-user"></i>个人中心
        </el-menu-item>
      </el-menu>
    </div>
    <div id="login-tap">
      <el-dialog :visible.sync="loginVisible" width="350px">
        <span slot="title">
          <img src="@/assets/logo.png" style="width:45px; height: 45px; margin-left:45%;" />
        </span>
        <el-form :label-position="labelPosition" :model="loginForm" :rules="rules" ref="loginForm">
          <el-form-item prop="username">
            <el-input
              v-model="loginForm.username"
              prefix-icon="el-icon-user-solid"
              :placeholder="requestName"
            ></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              prefix-icon="el-icon-key"
              :placeholder="requestPassword"
              type="password"
            ></el-input>
          </el-form-item>
          <el-form-item v-if="loginForm.username != ''" prop="validCode">
            <el-button @click="validCode()" v-if="vailSrc === ''">获取验证码</el-button>
            <el-row style="heigth:40px; line-height:0" v-if="vailSrc != ''">
              <el-col :span="5">
                <img height="40px" @click="validCode()" :src="vailSrc" />
              </el-col>
              <el-col :span="15">
                <el-input
                  style="margin-left: 51px"
                  v-model="loginForm.validCode"
                  prefix-icon="el-icon-key"
                  placeholder="请输入验证码"
                  type="number"
                ></el-input>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
        <el-divider></el-divider>
        <div slot="footer" class="dialog-footer">
          <el-button @click="clearForm('loginForm')">重置</el-button>
          <el-button @click="goRegister">注册</el-button>
          <el-button type="primary" @click="login">登陆</el-button>
        </div>
      </el-dialog>
    </div>
    <div id="register-tap">
      <el-dialog :visible.sync="registerVisible" width="350px">
        <span slot="title">
          <img src="@/assets/logo.png" style="width:45px; height: 45px; margin-left:45%;" />
        </span>
        <el-form
          :label-position="labelPosition"
          :model="loginForm"
          :rules="rules"
          ref="registerForm"
        >
          <el-form-item prop="username">
            <el-input
              v-model="loginForm.username"
              prefix-icon="el-icon-user-solid"
              :placeholder="requestName"
            ></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              prefix-icon="el-icon-key"
              placeholder="请输入密码"
              type="password"
            ></el-input>
          </el-form-item>
          <el-form-item prop="email">
            <el-input
              v-model="loginForm.email"
              prefix-icon="el-icon-s-promotion"
              placeholder="请输入邮箱"
              type="email"
            ></el-input>
          </el-form-item>
          <el-form-item prop="gender">
            <el-radio v-model="loginForm.gender" label="man">男</el-radio>
            <el-radio v-model="loginForm.gender" label="woman">女</el-radio>
          </el-form-item>
        </el-form>
        <el-divider></el-divider>
        <div slot="footer" class="dialog-footer">
          <el-button @click="clearForm('registerForm')">重置</el-button>
          <el-button @click="register" type="primary">注册</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import "@/assets/js/cookieUtils";
import { myMixin } from "@/assets/js/mixin";
export default {
  mixins: [myMixin],
  name: "NavHeader",
  data() {
    var checkEmail = (rule, value, callback) => {
      const mailReg = /^(\w)+(\.\w+)*@(\w)+((\.\w{2,3}){1,3})$/;
      if (!value) {
        return callback(new Error("邮箱不能为空"));
      }
      setTimeout(() => {
        if (mailReg.test(value)) {
          callback();
        } else {
          callback(new Error("请输入正确的邮箱格式"));
        }
      }, 100);
    };
    return {
      loginVisible: false,
      registerVisible: false,
      labelPosition: "left",
      requestName: "请输入用户名",
      requestPassword: "请输入密码",
      vailSrc: "",
      loginForm: {
        username: "",
        password: "",
        email: "",
        gender: "man",
        validCode: ""
      },
      rules: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" },
          { min: 6, max: 15, message: "长度在 6 到 15 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          { min: 6, max: 15, message: "长度在 6 到 15 个字符", trigger: "blur" }
        ],
        email: [{ validator: checkEmail, trigger: "blur" }],
        validCode: [
          { required: true, message: "验证码不能为空", trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    login() {
      this.$refs["loginForm"].validate(valid => {
        if (valid) {
          var form = this.loginForm;
          this.$axios
            .get(
              this.$const.domain +
                "/v1/user/login?username=" +
                form.username +
                "&password=" +
                form.password +
                "&validCode=" +
                form.validCode
            )
            .then(res => {
              if (res.data.code != 200) {
                this.$message(res.data.msg);
              } else {
                //注册成功 ..
                var data_ = res.data.data;
                this.setCookie(this.$const.tokenKey, data_.token, 7);
                this.$store.commit("setToken", data_.token);
                this.$store.commit("setUser", data_);
                form.username = data_.username;
                this.loginVisible = false;
              }
            })
            .catch(error => {
              console.log(error);
              this.$message.error("网络错误，不能访问");
            });
        } else {
          return valid;
        }
      });
    },
    goRegister() {
      this.loginVisible = false;
      this.registerVisible = true;
    },
    clearForm(formName) {
      this.vailSrc = "";
      this.$refs[formName].resetFields();
    },
    register() {
      this.$refs["registerForm"].validate(valid => {
        if (valid) {
          var form = this.loginForm;
          this.$axios
            .post(this.$const.domain + "/v1/user/save", {
              username: form.username,
              password: form.password,
              email: form.email,
              gender: form.gender
            })
            .then(res => {
              if (res.data.code != 200) {
                this.$message(res.data.msg);
              } else {
                //注册成功 ..
                var data_ = res.data.data;
                this.setCookie(this.$const.tokenKey, data_.token, 7);
                this.$store.commit("setToken", data_.token);
                form.username = data_.username;
                this.$store.commit("setUser", data_);
                this.registerVisible = false;
              }
            })
            .catch(error => {
              console.log(error);
              this.$message.error("网络错误，不能访问");
            });
        } else {
          return valid;
        }
      });
    },
    validCode() {
      var code = "data:image/jpeg;base64,";
      this.$axios
        .get(
          this.$const.domain +
            "/v1/user/validCode?username=" +
            this.loginForm.username
        )
        .then(res => {
          this.vailSrc = code + res.data.data;
        })
        .catch(error => {
          console.log(error);
          this.$message.error("网络错误，不能访问");
        });
      return this.vailSrc;
    }
  },
  mounted() {
    var token = this.getCookie(this.$const.tokenKey);
    if (token != null && token != "") {
      var username = this.$jwt(token).username;
      if (username != null && username != "") {
        this.loginForm.username = username;
        this.$store.commit("setToken", token);
      }

      if (
        this.$store.state.user == null ||
        this.$store.state.user.username == ""
      ) {
        this.$axios
          .get(this.$const.domain + "/v1/user/getUserInfo", {
            headers: this.headers
          })
          .then(res => {
            if (res.data.code == 200) {
              this.$store.commit("setUser", res.data.data);
            }
          });
      }
    }
  }
};
</script>
<style>
@media only screen and (min-width: 1024px) {
  .logoItem {
    margin-left: 45% !important;
  }
  .login-Item {
    margin-right: 10% !important;
  }
}

.el-dialog__body {
  padding: 10px 20px !important;
}
.nav {
  position: fixed;
  z-index: 1000;
  width: 100%;
  top: 0;
}
.el-menu--horizontal > .el-menu-item:not(.is-disabled):focus,
.el-menu--horizontal > .el-menu-item:not(.is-disabled):hover,
.el-menu--horizontal > .el-submenu .el-submenu__title:hover {
  background-color: rgb(90, 107, 119, 0.8) !important;
}
</style>